import React, { useState } from 'react';
import { 
  CloseOutlined, 
  DatabaseOutlined, 
  TableOutlined, 
  LinkOutlined,
  SafetyOutlined,
  BarChartOutlined,
  LoadingOutlined,
  ShareAltOutlined,
  DownloadOutlined,
  ArrowLeftOutlined,
  CheckCircleOutlined,
  WarningOutlined
} from '@ant-design/icons';
import { Tabs, Alert, Progress, Tooltip, Tag } from 'antd';
import ERDiagram from './ERDiagram';
import ErrorBoundary from '../error/ErrorBoundary';

const { TabPane } = Tabs;

const TableDetailsView = ({ tableName, tableData, onBack }) => {
  const renderColumnStats = (column) => {
    return (
      <div className="column-stats">
        <div className="stat-row">
          <span className="stat-label">数据类型:</span>
          <span className="stat-value">{column.data_type}</span>
        </div>
        {column.distinct_count !== undefined && (
          <div className="stat-row">
            <span className="stat-label">唯一值数量:</span>
            <span className="stat-value">{column.distinct_count}</span>
          </div>
        )}
        {column.null_count !== undefined && (
          <div className="stat-row">
            <span className="stat-label">空值数量:</span>
            <span className="stat-value">{column.null_count}</span>
          </div>
        )}
        {column.min_value !== undefined && (
          <div className="stat-row">
            <span className="stat-label">最小值:</span>
            <span className="stat-value">{column.min_value}</span>
          </div>
        )}
        {column.max_value !== undefined && (
          <div className="stat-row">
            <span className="stat-label">最大值:</span>
            <span className="stat-value">{column.max_value}</span>
          </div>
        )}
        {column.mean_value !== undefined && (
          <div className="stat-row">
            <span className="stat-label">平均值:</span>
            <span className="stat-value">{column.mean_value}</span>
          </div>
        )}
        {column.median_value !== undefined && (
          <div className="stat-row">
            <span className="stat-label">中位数:</span>
            <span className="stat-value">{column.median_value}</span>
          </div>
        )}
        {column.std_dev !== undefined && (
          <div className="stat-row">
            <span className="stat-label">标准差:</span>
            <span className="stat-value">{column.std_dev}</span>
          </div>
        )}
        {column.sample_values && (
          <div className="stat-row">
            <span className="stat-label">样本值:</span>
            <span className="stat-value">{column.sample_values}</span>
          </div>
        )}
      </div>
    );
  };

  const renderContentAnalysis = () => {
    if (!tableData.content_analysis || Object.keys(tableData.content_analysis).length === 0) {
      return <div className="no-analysis">没有内容分析数据</div>;
    }
    
    return Object.entries(tableData.content_analysis).map(([columnName, analysis]) => (
      <div key={columnName} className="analysis-section">
        <h4 className="analysis-title">{columnName} 分析</h4>
        <div className="analysis-content">
          {Object.entries(analysis).map(([key, value]) => (
            <div key={key} className="analysis-item">
              <span className="analysis-key">{key}:</span>
              <span className="analysis-value">{Array.isArray(value) ? value.join(', ') : value}</span>
            </div>
          ))}
        </div>
      </div>
    ));
  };

  // 渲染数据质量问题
  const renderDataQuality = () => {
    if (!tableData.data_quality || Object.keys(tableData.data_quality).length === 0) {
      return <div className="no-quality">未检测到数据质量问题</div>;
    }
    
    return Object.entries(tableData.data_quality).map(([issueType, issues]) => (
      <div key={issueType} className="issue-type">
        <h4>{issueType}</h4>
        <ul>
          {issues.map((issue, index) => (
            <li key={index}>{issue}</li>
          ))}
        </ul>
      </div>
    ));
  };

  // 计算数据质量评分
  const calculateQualityScore = () => {
    // 简单模拟评分逻辑，实际应用中应根据具体规则计算
    if (!tableData.data_quality) return 100;
    
    const issueCount = Object.values(tableData.data_quality)
      .reduce((count, issues) => count + issues.length, 0);
    
    return Math.max(0, 100 - issueCount * 5);
  };

  return (
    <div className="table-details-view">
      <div className="table-header">
        <button className="back-btn" onClick={onBack}>
          <ArrowLeftOutlined /> 返回表列表
        </button>
        <h2>{tableName}</h2>
      </div>
      
      <div className="metadata-section">
        <h3>元数据信息</h3>
        <div className="metadata-grid">
          <div className="metadata-item">
            <span className="meta-label">行数:</span>
            <span className="meta-value">{tableData.metadata.row_count}</span>
          </div>
          <div className="metadata-item">
            <span className="meta-label">列数:</span>
            <span className="meta-value">{tableData.metadata.column_count}</span>
          </div>
          <div className="metadata-item">
            <span className="meta-label">主键:</span>
            <span className="meta-value">{tableData.metadata.primary_key || '无'}</span>
          </div>
          <div className="metadata-item">
            <span className="meta-label">更新时间:</span>
            <span className="meta-value">
              {new Date(tableData.metadata.updated_at).toLocaleString()}
            </span>
          </div>
        </div>
      </div>
      
      <div className="quality-summary">
        <div className="quality-score">
          <div className="score-value">{calculateQualityScore()}/100</div>
          <Progress 
            percent={calculateQualityScore()} 
            status={calculateQualityScore() > 80 ? "success" : "exception"}
            strokeColor={calculateQualityScore() > 80 ? "#52c41a" : "#ff4d4f"}
          />
          <div className="score-label">数据质量评分</div>
        </div>
        <div className="quality-stats">
          {tableData.data_quality && Object.keys(tableData.data_quality).length > 0 ? (
            <>
              <div className="stat-item error">
                <WarningOutlined />
                <span>{Object.values(tableData.data_quality).reduce((count, issues) => count + issues.length, 0)} 个问题</span>
              </div>
              <div className="stat-item">
                <CheckCircleOutlined />
                <span>{tableData.metadata.column_count - Object.keys(tableData.data_quality).length} 列正常</span>
              </div>
            </>
          ) : (
            <div className="stat-item success">
              <CheckCircleOutlined />
              <span>所有列数据质量良好</span>
            </div>
          )}
        </div>
      </div>
      
      <div className="columns-section">
        <h3>列信息</h3>
        <div className="columns-list">
          {tableData.columns.map(column => (
            <div key={column.id} className="column-card">
              <div className="column-header">
                <span className="column-name">{column.column_name}</span>
                <div className="column-flags">
                  {column.is_primary && <span className="flag primary">主键</span>}
                  {column.is_foreign && <span className="flag foreign">外键</span>}
                </div>
              </div>
              {renderColumnStats(column)}
            </div>
          ))}
        </div>
      </div>
      
      <div className="data-quality-section">
        <h3 style={{ color: '#ff4d4f', borderBottom: '1px solid #ffccc7', paddingBottom: 8 }}>
          <SafetyOutlined style={{ marginRight: 8 }} />
          数据质量分析
        </h3>
        {renderDataQuality()}
      </div>
      
      <div className="analysis-section">
        <h3>内容分析</h3>
        {renderContentAnalysis()}
      </div>
    </div>
  );
};

const TaskDetailsModal = ({ taskDetails, visible, onClose, loading }) => {
  const [activeTab, setActiveTab] = useState('overview');
  const [selectedTable, setSelectedTable] = useState(null);
  
  if (taskDetails?.error) {
    return (
      <div className="modal-backdrop">
        <div className="modal-content">
          <div className="modal-header">
            <h3>任务详情</h3>
            <button className="close-btn" onClick={onClose}>×</button>
          </div>
          <div className="modal-body">
            <Alert type="error" message="加载失败" description={taskDetails.error} />
          </div>
        </div>
      </div>
    );
  }
  
  if (!taskDetails) return null;

  // 渲染摘要统计
  const renderSummaryStats = () => (
    <div className="summary-stats">
      <div className="stat-item">
        <div className="stat-label">探查表数</div>
        <div className="stat-value">{taskDetails.summary.table_count}</div>
      </div>
      
      <div className="stat-item">
        <div className="stat-label">关系数量</div>
        <div className="stat-value">{taskDetails.summary.relationship_count}</div>
      </div>
      
      <div className="stat-item">
        <div className="stat-label">总行数</div>
        <div className="stat-value">{taskDetails.summary.total_row_count}</div>
      </div>
      
      <div className="stat-item">
        <div className="stat-label">数据质量问题</div>
        <div className="stat-value error">{taskDetails.summary.total_issues}</div>
      </div>
      
      <div className="stat-item">
        <div className="stat-label">平均质量评分</div>
        <div className="stat-value" style={{ color: '#52c41a' }}>92/100</div>
      </div>
    </div>
  );

  // 渲染关系表格
  const renderRelationships = () => {
    if (!taskDetails.relationships || taskDetails.relationships.length === 0) {
      return <div className="empty-state">未发现关系探查结果</div>;
    }
    
    return (
      <div className="relationships-table">
        <table>
          <thead>
            <tr>
              <th>源表</th>
              <th>源列</th>
              <th>目标表</th>
              <th>目标列</th>
              <th>数据完整性</th>
            </tr>
          </thead>
          <tbody>
            {taskDetails.relationships.map((rel, index) => (
              <tr key={index}>
                <td>{rel.source_table}</td>
                <td>{rel.source_column}</td>
                <td>{rel.target_table}</td>
                <td>{rel.target_column}</td>
                <td>
                  {rel.orphan_pct === 0 ? (
                    <Tag color="green">完整</Tag>
                  ) : (
                    <Tooltip title={`孤立记录: ${rel.orphans} (${(rel.orphan_pct * 100).toFixed(2)}%)`}>
                      <Tag color="orange">部分缺失</Tag>
                    </Tooltip>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  };

  // 渲染表详情
  const renderTables = () => {
    if (!taskDetails.tables || Object.keys(taskDetails.tables).length === 0) {
      return <div className="empty-state">未探查到任何表</div>;
    }
    
    // 计算表的数据质量评分
    const calculateTableQuality = (tableData) => {
      if (!tableData.data_quality) return 100;
      const issueCount = Object.values(tableData.data_quality).reduce((count, issues) => count + issues.length, 0);
      return Math.max(0, 100 - issueCount * 5);
    };
    
    return (
      <div className="tables-list">
        {Object.entries(taskDetails.tables).map(([tableName, tableData]) => (
          <div 
            key={tableName} 
            className="table-card"
            onClick={() => setSelectedTable({ name: tableName, data: tableData })}
          >
            <div className="table-header">
              <TableOutlined style={{ marginRight: 8 }} />
              <h3>{tableName}</h3>
              <div className="table-stats">
                <span>行数: {tableData.metadata.row_count}</span>
                <span>列数: {tableData.metadata.column_count}</span>
                {tableData.data_quality && Object.keys(tableData.data_quality).length > 0 && (
                  <span style={{ color: '#ff4d4f' }}>
                    问题: {Object.values(tableData.data_quality).reduce((count, issues) => count + issues.length, 0)}个
                  </span>
                )}
              </div>
            </div>
            
            <div className="table-columns">
              <h4>列信息</h4>
              <div className="columns-grid">
                {tableData.columns.slice(0, 4).map(column => (
                  <div key={column.id} className="column-item">
                    <div className="column-name">{column.column_name}</div>
                    <div className="column-type">{column.data_type}</div>
                    <div className="column-stats">
                      {column.is_primary && <span className="badge primary">主键</span>}
                      {column.is_foreign && <span className="badge foreign">外键</span>}
                    </div>
                  </div>
                ))}
                {tableData.columns.length > 4 && (
                  <div className="column-item more-columns">
                    +{tableData.columns.length - 4} 更多列...
                  </div>
                )}
              </div>
            </div>
            
            <div className="quality-summary">
              <Progress 
                percent={calculateTableQuality(tableData)} 
                status={calculateTableQuality(tableData) > 80 ? "success" : "exception"}
                strokeColor={calculateTableQuality(tableData) > 80 ? "#52c41a" : "#ff4d4f"}
              />
              <div className="quality-label">
                数据质量评分: {calculateTableQuality(tableData)}/100
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  };

  // 渲染业务规则
  const renderBusinessRules = () => {
    if (!taskDetails.business_rules || taskDetails.business_rules.length === 0) {
      return <div className="empty-state">未配置业务规则检查</div>;
    }
    
    return (
      <div className="rules-list">
        {taskDetails.business_rules.map((rule, index) => (
          <div key={index} className="rule-item">
            <div className="rule-header">
              <SafetyOutlined style={{ marginRight: 8 }} />
              <h4>{rule.rule_name}</h4>
              <span className={`violation-count ${rule.violation_count > 0 ? 'error' : 'success'}`}>
                {rule.violation_count} 个违规
              </span>
            </div>
            <p className="rule-description">{rule.description}</p>
          </div>
        ))}
      </div>
    );
  };

  // 渲染ER关系图（安全版本）
  const SafeERDiagram = ({ tables, relationships }) => {
    return (
      <div className="safe-er-diagram-container">
        <ErrorBoundary>
          <ERDiagram tables={tables} relationships={relationships} />
        </ErrorBoundary>
      </div>
    );
  };

  return (
    <div className="modal-backdrop">
      <div className="modal-content task-details-modal">
        <div className="modal-header">
          <h2>
            <DatabaseOutlined style={{ marginRight: 10 }} />
            探查任务详情
          </h2>
          <button className="close-btn" onClick={onClose}>
            <CloseOutlined />
          </button>
        </div>
        
        <div className="modal-body">
          {selectedTable ? (
            <TableDetailsView 
              tableName={selectedTable.name}
              tableData={selectedTable.data}
              onBack={() => setSelectedTable(null)}
            />
          ) : (
            <Tabs 
              activeKey={activeTab} 
              onChange={setActiveTab}
              className="details-tabs"
            >
              <TabPane 
                tab={
                  <span>
                    <BarChartOutlined />
                    概览
                  </span>
                } 
                key="overview"
              >
                <h3>探查摘要</h3>
                {renderSummaryStats()}
              </TabPane>
              
              <TabPane 
                tab={
                  <span>
                    <TableOutlined />
                    表详情
                  </span>
                } 
                key="tables"
              >
                <h3>探查表结果</h3>
                {renderTables()}
              </TabPane>
              
              <TabPane 
                tab={
                  <span>
                    <LinkOutlined />
                    关系
                  </span>
                } 
                key="relationships"
              >
                <h3>关系探查结果</h3>
                {renderRelationships()}
              </TabPane>
              
              <TabPane 
                tab={
                  <span>
                    <SafetyOutlined />
                    业务规则
                  </span>
                } 
                key="rules"
              >
                <h3>业务规则检查结果</h3>
                {renderBusinessRules()}
              </TabPane>
            </Tabs>
          )}
        </div>
      </div>
    </div>
  );
};

export default TaskDetailsModal;